package com.feng.zhihao.apigeteway.gateway.bean.impl.FIELD_TYPE;

import org.springframework.stereotype.Component;

import com.feng.zhihao.apigeteway.entity.InterfaceFieldInfo;
import com.feng.zhihao.apigeteway.gateway.bean.FIELD_TYPE;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.ReUtil;
import com.xiaoleilu.hutool.util.StrUtil;

@Component("FIELD_TYPE_REQ_SIGNATURE")
public class FIELD_TYPE_REQ_SIGNATURE implements FIELD_TYPE {

	@Override
	public String validatorField(InterfaceFieldInfo fieldInfo, Object value) {
		StringBuffer sb=new StringBuffer();
		if(!(value instanceof String)){
			sb.append(StrUtil.format("字段:({}), 无法识别为请求签名:({});\r\n",fieldInfo.getInterfaceFieldName(),value.toString()));
		}
		String v=(String) value;
		fieldInfo.getFieldLimitInfos()
		.stream()
		.forEach((fi) -> {
			if(fi.getLimitLengthMax() != null && v.length() > fi.getLimitLengthMax()){
				sb.append(StrUtil.format("字段:({}),值:({}),长度:({}), 超过了最大长度:({});\r\n",fieldInfo.getInterfaceFieldName(),v,v.length(),fi.getLimitLengthMax()));
			}

			if(fi.getLimitLengthMin() != null && v.length() > fi.getLimitLengthMin()){
				sb.append(StrUtil.format("字段:({}),值:({}),长度:({}), 小于最小长度:({});\r\n",fieldInfo.getInterfaceFieldName(),v,v.length(),fi.getLimitLengthMin()));
			}
			if(!StrUtil.isBlank(fi.getLimitEnum())){
				String[] limitEnum=fi.getLimitEnum().split("@fzh@");
				if(!ArrayUtil.contains(limitEnum, value)){
					sb.append(StrUtil.format("字段:({}),值:({}), 不在限制值中:({});\r\n",fieldInfo.getInterfaceFieldName(),value.toString(),ArrayUtil.join(limitEnum, "),(")));
				}
			}
			if(!ReUtil.isMatch(fi.getLimitRegular(), v)){
				sb.append(StrUtil.format("字段:({}),值:({}),不匹配正则表达式:({});\r\n",fieldInfo.getInterfaceFieldName(),v,fi.getLimitRegular()));
			}
		});
		return sb.toString();
	}

}
